package com.bcxk.util;

import com.bcxk.entity.dto.Homestay;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Component
public class EsUtils {

    @Autowired
    RestHighLevelClient client;

    public Map<String, Object> getById(String index, String id) throws IOException {
        GetRequest request = new GetRequest(index,id);
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        if (response.isExists()) {
            return response.getSource();
        }
        return null;
    }


    public List<String> query(String index,String queryWord,String word) throws IOException {
        SearchRequest request = new SearchRequest(index);

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery(queryWord, word));

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.sort(SortBuilders.fieldSort("id").order(SortOrder.ASC));
        searchSourceBuilder.from(0).size(9).query(boolQueryBuilder);

        request.searchType(SearchType.DEFAULT).source(searchSourceBuilder);

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        List<String> list = new LinkedList<>();
        for (SearchHit hit : response.getHits().getHits()) {
            list.add(hit.getSourceAsString());
        }
        return list;
    }

}
